package com.wujilin.okra.fragment;

import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;
import static android.content.DialogInterface.BUTTON_POSITIVE;
import static com.wujilin.okra.Okra.EXTRA_OBJECTIVE_GRADE;
import static com.wujilin.okra.Okra.EXTRA_OBJECTIVE_ID;
import static com.wujilin.okra.Okra.EXTRA_OBJECTIVE_TIME;
import static com.wujilin.okra.Okra.FORMATTER_DATE_TIME;
import static com.wujilin.okra.Okra.F_GRADE;
import static com.wujilin.okra.Okra.F_TIME;
import static com.wujilin.okra.Okra.T_OBJECTIVE;

import org.joda.time.DateTime;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import com.wujilin.okra.database.Sql;

public abstract class KeyResultDialogFragment extends DialogFragment implements DialogInterface.OnClickListener {
	
	/**
	 * 
	 * 
	 * @param dialog
	 * @param args The fragment's arguments
	 */
	public abstract void onClickPositiveButton(DialogInterface dialog, Bundle args);
	public abstract void onCreateDialog(AlertDialog.Builder builder);
	
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		onCreateDialog(builder);
		builder.setPositiveButton(android.R.string.ok, this).setNegativeButton(android.R.string.cancel, null);
		return builder.create();
	}
	
	@Override
	public void onClick(final DialogInterface dialog, int which) {
		if (which == BUTTON_POSITIVE) {
			final Intent data = new Intent();
			boolean success = Sql.run(new Runnable() {
				@Override
				public void run() {
					Bundle args = getArguments();
					onClickPositiveButton(dialog, args);
					long objectiveId = args.getLong(EXTRA_OBJECTIVE_ID, 0);
					String sql = "select avg(grade) grade from key_result where objective_id=?";
					float gradeAvg = Sql.floatValue(sql, objectiveId + "");
					String time = DateTime.now().toString(FORMATTER_DATE_TIME);
					Sql.update(T_OBJECTIVE, objectiveId, F_GRADE, gradeAvg, F_TIME, time);
					data.putExtra(EXTRA_OBJECTIVE_GRADE, gradeAvg + "");
					data.putExtra(EXTRA_OBJECTIVE_TIME, time);
				}
			});
			int resultCode = success ? RESULT_OK : RESULT_CANCELED;
			getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, data);
		}
	}
}
